//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include <winhack.h>
#include <elasys_server.h>
#include <elapi.h>
#include <stdlib.h>
#include <linknode.h>
#include <msgqueue.h>

CMsgQueue::CMsgQueue()
{
    m_hEvent     = NULL;
    m_set = m_get = 0;
    m_hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
}

CMsgQueue::~CMsgQueue()
{
    CloseHandle(m_hEvent);
    m_hEvent = NULL;
}

// enqueue a message
void CMsgQueue::Enqueue(InputEvent *pMsg)
{

    m_set = (m_set + 1) % 64;

    memcpy(&m_events[m_set], pMsg, sizeof(InputEvent));

    SetEvent(m_hEvent);
    ResetEvent(m_hEvent);
}

// dequeue a message
InputEvent* CMsgQueue::Dequeue()
{
    while (m_set == m_get) {
        WaitForSingleObject(m_hEvent, (DWORD)INFINITE);
    }

    int i = m_get;
    i = (i + 1) % 64;
    m_get = i;

    ResetEvent(m_hEvent);
    return &m_events[i];
}
